package com.jingzhe.security.shiro;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jingzhe.biz.sys.domain.SysUser;
import com.jingzhe.biz.sys.service.ISysUserService;
import com.jingzhe.core.constant.GlobalConstant;
import com.jingzhe.security.shiro.session.SessionDAO;

/**
 * 系统安全实现类
 * @author wanghj
 *
 */
public class JingzheRealm extends AuthorizingRealm {
    private final static Logger  LOGGER = LoggerFactory.getLogger(JingzheRealm.class);
    
    @Resource
    private SessionDAO sessionDao;
    
    @Resource
    private ISysUserService sysUserService;
    


    /**
     * 为当前登录的Subject授予角色和权限 
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        return null;
    }

    /** 
     * 验证当前登录的Subject 
     * 该方法的调用时机为登录方法中执行Subject.login()时 调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        int activeSessionSize = sessionDao.getActiveSessions(false).size();
        if (LOGGER.isDebugEnabled()){
            LOGGER.debug("login submit, active session size: {}, username: {}", activeSessionSize, token.getUsername());
        }
        // 校验登录验证码
//        throw new AuthenticationException("msg:验证码错误, 请重试.");
        
     // 校验用户名密码
        SysUser sysUser = sysUserService.selectByLoginName(token.getUsername());
        if (sysUser != null) {
            if (GlobalConstant.NO.equals(sysUser.getLoginFlag())){
                throw new LockedAccountException("该已帐号禁止登录。");
            }
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                    sysUser.getId(), sysUser.getPassword(), getName());
            info.setCredentialsSalt(ByteSource.Util.bytes(sysUser.getId() + GlobalConstant.getConfig("salt")));
            return info;
        } else {
            return null;
        }
        
    }
    
    /** 
     * 将一些数据放到ShiroSession中,以便于其它地方使用 
     * @see  比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 
     */  
    private void setSession(Object key, Object value){  
        Subject currentUser = SecurityUtils.getSubject();  
        if(null != currentUser){  
            Session session = currentUser.getSession();  
            System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");  
            if(null != session){  
                session.setAttribute(key, value);  
            }  
        }  
    }  

}
